/************************************************************************

								Heroes IV
					  Copyright 1998-2000, The 3DO Company

	------------------------------------------------------------------
							 profile.cpp

	$Header: /Heroes4/Game/profile.cpp $

	$NoKeywords: $

 ************************************************************************/

// kill the 255+ character identifier warning.  Templates tend to exceed that easily.
#include "precompiled.h"
#pragma warning( disable: 4786 )

#include "profile.h"

#include <algorithm>
#include <time.h>
#include <vector>
#include <windows.h>
#include "game_time.h"

static std::vector<t_profile_marker*> g_profile_markers;
static bool g_profiling_enabled = true;

void enable_profiling( bool arg )
{
	g_profiling_enabled = arg; 
}

bool profiling_is_enabled()
{
	return g_profiling_enabled;
}

t_profile_marker::t_profile_marker( std::string const& new_label,  std::string const& line )
{
	m_file_line = line;
	m_label = new_label;
	m_hits = 0;
	m_time_total = 0;
}

void t_profile_marker::update( long new_time )
{
	if (!g_profiling_enabled)
		return;
	if (m_hits == 0)
		g_profile_markers.push_back( this );
	m_hits++;
	m_time_total += new_time;
}

t_profile_timer::t_profile_timer( t_profile_marker& new_marker, bool start_timer )
                  : m_marker(new_marker)
{
	m_running = false;
	if (start_timer)
		start();
}

t_profile_timer::~t_profile_timer()
{
	stop();
}

void t_profile_timer::start()
{
	if (m_running)
		return;
	m_running = true;
	m_start_time = get_time();
}

void t_profile_timer::stop()
{
	if (!m_running)
		return;
	m_running = false;
	m_marker.update( get_time() - m_start_time );
}

class t_compare_profiles
{
public:
	bool operator()( const t_profile_marker* x, const t_profile_marker* y )
	{
		return x->get_time_total() > y->get_time_total();
	}
};

void dump_profile_markers()
{
	std::sort( g_profile_markers.begin(), g_profile_markers.end(), 
		       t_compare_profiles() );
	long i;

	for (i = 0; i < g_profile_markers.size(); i++)
	{
		OutputDebugString( format_string( "%50s : %7i msec, %5i hits %7i msec each: %s\n", 
			               g_profile_markers[i]->get_file_line(),
			               g_profile_markers[i]->get_time_total(),
			               g_profile_markers[i]->get_hits(), 
						   g_profile_markers[i]->get_time_total()
						   / g_profile_markers[i]->get_hits(),
					       g_profile_markers[i]->get_label() ).c_str() );
	}
}
